package com.bjx.flow.mmx.task.node;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.expression.ExpressionUtil;
import com.bjx.flow.mmx.bean.MmxFlowData;
import com.bjx.flow.mmx.bean.MmxNodeData;
import com.bjx.flow.mmx.constant.MmxNodeConstant;
import com.bjx.flow.mmx.domain.bo.MmxNodeFlowBO;
import com.bjx.flow.mmx.task.MmxAbstractNodeFlowDispose;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * @desc: 包容网关节点
 * @author: liushuai
 * @date: 2023/1/31 15:23
 */
@Service(MmxNodeConstant.INCLUSIVE_GATEWAY)
public class MmxInclusiveGatewayNodeFlowDispose extends MmxAbstractNodeFlowDispose {
    @Override
    public MmxNodeFlowBO execute(MmxFlowData flowObj, MmxNodeData currentNode, Map<String, Object> variables) {
        List<MmxNodeData> targerNode = this.getTargerNode(flowObj, currentNode);
        if(targerNode.size() == 0){
            throw new RuntimeException("包容网关不能没有目标节点");
        }
        List<MmxNodeData> list = new ArrayList<>();
        for(MmxNodeData nodeData : targerNode) {
            if(TRANSIT_NODE.contains(nodeData.getType())){
                throw new RuntimeException("包容网关目标不能为流转型节点");
            }
            if(StrUtil.isEmpty(nodeData.getCondition())){
                list.add(nodeData);
                continue;
            }
            //根据表达式判断是否符合流转条件
            Boolean condition = (Boolean) ExpressionUtil.eval(nodeData.getCondition(), variables);
            if(condition){
                list.add(nodeData);
            }
        }
        HashSet set = new HashSet();
        //通过节点id判断是否存在多个相同的节点
        for(MmxNodeData nodeData : list) {
            set.add(nodeData.getId());
        }
        if(set.size() != list.size()){
            throw new RuntimeException("包容网关不能多条连线连接同一个节点");
        }
        return MmxNodeFlowBO.builder()
                .nodeType(MmxNodeConstant.INCLUSIVE_GATEWAY)
                .nodeData(list)
                .build();
    }

}
